﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
using System.Web.UI.HtmlControls;

namespace DevSky.WebParts.YouTube
{
    public class YouTubeManager
    {
        public static List<SingleVideo> GetVideoForChannel(string channelName)
        {
            List<SingleVideo> videoList = new List<SingleVideo>();
            XmlDocument rss = null;
            XmlNamespaceManager namespaceManager = null;
            WebRequest request = WebRequest.Create(new Uri(string.Format(YouTubeVideo.YOUTUBERSS, channelName)));
            WebResponse rssResponse = null;
            try
            {
                rssResponse = request.GetResponse();
                {
                    using (Stream rssStream = rssResponse.GetResponseStream())
                    {
                        rss = new XmlDocument();
                        namespaceManager = new XmlNamespaceManager(rss.NameTable);
                        namespaceManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                        namespaceManager.AddNamespace("media", "http://search.yahoo.com/mrss/");
                        namespaceManager.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/");
                        namespaceManager.AddNamespace("gd", "http://schemas.google.com/g/2005");
                        namespaceManager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
                        rss.Load(rssStream);
                    }
                }
            }
            catch (Exception exc)
            {
            }
            finally
            {
                rssResponse.Close();
            }
            if (rss != null)
            {
                XmlNodeList entries = rss.SelectNodes("//atom:feed/atom:entry", namespaceManager);
                SingleVideo videoEntry = null;
                if (entries != null)
                {
                    string videoID = string.Empty;
                    foreach (XmlNode video in entries)
                    {
                        videoEntry = CreateVideoEntry(video, namespaceManager);
                        if (videoEntry != null)
                            videoList.Add(videoEntry);
                    }
                }
            }
            return videoList;
        }

        public static SingleVideo GetVideoInformation(string id)
        {
            SingleVideo video = null;
            string requestURL = string.Format("http://gdata.youtube.com/feeds/api/videos/{0}?v=2", id);
            XmlNamespaceManager namespaceManager = null;
            WebRequest request = WebRequest.Create(new Uri(requestURL));
            WebResponse rssResponse = null;
            XmlDocument responseXML = null;
            try
            {
                rssResponse = request.GetResponse();
                {
                    using (Stream rssStream = rssResponse.GetResponseStream())
                    {
                        responseXML = new XmlDocument();
                        namespaceManager = new XmlNamespaceManager(responseXML.NameTable);
                        namespaceManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                        namespaceManager.AddNamespace("media", "http://search.yahoo.com/mrss/");
                        namespaceManager.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/");
                        namespaceManager.AddNamespace("gd", "http://schemas.google.com/g/2005");
                        namespaceManager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
                        responseXML.Load(rssStream);
                    }
                }
            }
            catch (Exception exc)
            {
            }
            finally
            {
                rssResponse.Close();
            }
            if (responseXML != null)
            {
                XmlNode entry = responseXML.SelectSingleNode("//atom:entry", namespaceManager);
                if (entry != null)
                {
                    video = CreateVideoEntry(entry, namespaceManager);
                }
            }
            return video;
        }

        private static SingleVideo CreateVideoEntry(XmlNode entry, XmlNamespaceManager namespaceManager)
        {
            SingleVideo video = new SingleVideo();
            video.ID = entry.SelectSingleNode("atom:id", namespaceManager).InnerText;
            if (video.ID.StartsWith("tag:youtube"))
                video.ID = video.ID.Substring(video.ID.LastIndexOf(':') + 1);
            else
                video.ID = video.ID.Substring(video.ID.LastIndexOf('/') + 1);
            video.Title = entry.SelectSingleNode("atom:title", namespaceManager).InnerText;
            video.Published = DateTime.Parse(entry.SelectSingleNode("atom:published", namespaceManager).InnerText);
            video.Updated = DateTime.Parse(entry.SelectSingleNode("atom:updated", namespaceManager).InnerText);
            XmlNodeList thumbnailList = entry.SelectSingleNode("media:group", namespaceManager).SelectNodes("media:thumbnail", namespaceManager);
            foreach (XmlNode thumb in thumbnailList)
                video.Thumbnails.Add(new VideoThumbnail() { Url = thumb.Attributes["url"].Value, Height = thumb.Attributes["height"].Value, Width = thumb.Attributes["width"].Value });
            return video;
        }

        public static string IFrameURL(string link, bool ssl, bool similarVideos)
        {
            string url = string.Empty;
            string protocol = "http";
            if (ssl)
                protocol = "https";
            if (similarVideos)
                url = string.Format("{1}://www.youtube.com/embed/{0}", link, protocol);
            else
                url = string.Format("{1}://www.youtube.com/embed/{0}?rel=0", link, protocol);
            return url;
        }

        public static string ObjectEmbeddingUrl(string link, bool ssl, bool similarVideos)
        {
            string url = string.Empty;
            string protocol = "http";
            if (ssl)
                protocol = "https";
            if (similarVideos)
                url = string.Format("{1}://www.youtube.com/v/{0}?version=3&amp;hl=de_DE", link, protocol);
            else
                url = string.Format("{1}://www.youtube.com/v/{0}?version=3&amp;hl=de_DE&amp;rel=0", link, protocol);
            return url;
        }

        public static HtmlGenericControl BuildYoutTubeLink(bool useIFrame, string width, string height, string link, bool allowFullScreen, bool ssl, bool similarVideos)
        {
            if (useIFrame)
                return CreateYouTubeIFrame(width, height, link, allowFullScreen, ssl, similarVideos);
            else
                return CreateYouTubeObject(width, height, link, allowFullScreen, ssl, similarVideos);
        }

        private static HtmlGenericControl CreateYouTubeIFrame(string width, string height, string link, bool allowFullScreen, bool ssl, bool similarVideos)
        {
            HtmlGenericControl iframe = new HtmlGenericControl("iframe");
            iframe.ID = "youtubeVideoIframe";
            iframe.InnerText = "youtubeVideoIframe";
            iframe.Attributes.Add("width", width);
            iframe.Attributes.Add("height", height);
            iframe.Attributes.Add("src", IFrameURL(link,ssl, similarVideos));
            iframe.Attributes.Add("frameborder", "0");
            return iframe;
        }

        private static HtmlGenericControl CreateYouTubeObject(string width, string height, string link, bool allowFullScreen, bool ssl, bool similarVideos)
        {
            HtmlGenericControl objectTage = new HtmlGenericControl("object");
            objectTage.Attributes.Add("width", width);
            objectTage.Attributes.Add("height", height);

            HtmlGenericControl paramTag = new HtmlGenericControl("param");
            paramTag.Attributes.Add("movie", ObjectEmbeddingUrl(link, ssl, similarVideos));
            objectTage.Controls.Add(paramTag);
            paramTag = new HtmlGenericControl("param");
            paramTag.Attributes.Add("allowFullScreen", allowFullScreen.ToString());
            objectTage.Controls.Add(paramTag);

            HtmlGenericControl embTag = new HtmlGenericControl("embed");
            embTag.Attributes.Add("movie", ObjectEmbeddingUrl(link, ssl, similarVideos));
            embTag.Attributes.Add("type", "application/x-shockwave-flash");
            embTag.Attributes.Add("width", width);
            embTag.Attributes.Add("height", height);
            embTag.Attributes.Add("allowscriptaccess", "always");
            embTag.Attributes.Add("allowfullscreen", allowFullScreen.ToString());
            objectTage.Controls.Add(embTag);

            return objectTage;
        }
    }
}
